import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  getReviewWords,
  type ReviewWord,
  type ReviewWordsParams,
} from '@/api/dcyx/dcyx_memory_tracking.api'

export const useDcyxMemoryTrackingStore = defineStore(
  'dcyxMemoryTracking',
  () => {
    // 状态
    const reviewWords = ref<ReviewWord[]>([])
    const loading = ref(false)
    const currentSource = ref<'znjy' | 'zntx' | 'znmx'>('znjy')
    const selectedUnitId = ref<number | undefined>(undefined)

    // 计算属性
    const totalWords = computed(() => reviewWords.value.length)
    const needReviewWords = computed(() =>
      reviewWords.value.filter((word) => word.status === 1),
    )
    const needReviewCount = computed(() => needReviewWords.value.length)

    // 方法
    const fetchReviewWords = async (params: ReviewWordsParams) => {
      try {
        loading.value = true
        const response = await getReviewWords(params)
        reviewWords.value = response
      } catch (error) {
        console.error('获取复习单词出错:', error)
        reviewWords.value = []
      } finally {
        loading.value = false
      }
    }

    const setCurrentSource = (source: 'znjy' | 'zntx' | 'znmx') => {
      currentSource.value = source
    }

    const setSelectedUnitId = (unitId: number | undefined) => {
      selectedUnitId.value = unitId
    }

    const loadReviewWords = async (programId: number) => {
      const params: ReviewWordsParams = {
        programId,
        source: currentSource.value,
        unitId: selectedUnitId.value,
      }
      await fetchReviewWords(params)
    }

    const reset = () => {
      reviewWords.value = []
      loading.value = false
      currentSource.value = 'znjy'
      selectedUnitId.value = undefined
    }

    return {
      // 状态
      reviewWords,
      loading,
      currentSource,
      selectedUnitId,

      // 计算属性
      totalWords,
      needReviewWords,
      needReviewCount,

      // 方法
      fetchReviewWords,
      setCurrentSource,
      setSelectedUnitId,
      loadReviewWords,
      reset,
    }
  },
)
